import Vue from 'vue'
import VueRouter from 'vue-router'
import {isEmpty} from "element-ui/src/utils/util";


import store from '../store'

import * as Methods from '../store/methods.const'

Vue.use(VueRouter)

//解决重复进入同一个路由问题
// Error: Avoided redundant navigation to current location
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const LoginRegister = () => import('views/loginRegister/LoginRegister');


const Login = ()=> import('views/loginRegister/components/Login');
const Register = ()=> import('views/loginRegister/components/Register');



const Home = () => import('views/home/Home');
const Welcome = () => import('views/home/Welcome');

const GoodList = () => import('views/home/good/GoodList');
const CategoryList = () => import('views/home/good/CategoryList');

const UserList = () => import('views/home/user/UserList');
const RightList = () => import('views/home/permission/RightList')

const RoleList = () => import('views/home/permission/RoleList')

const routes = [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path:'/loginRegister',
      component:LoginRegister,
      redirect: '/login',
      children:[
        {
          path: '/login',
          name: '登录',
          component: Login
        },
        {
          path:'/register',
          name:'注册',
          component:Register
        }
      ]
    },
    {
      path:'/home',
      component: Home,
      redirect:'/welcome',
      children: [
        {
          path:'/welcome',
          name:'欢迎',
          component:Welcome
        },
        {
          path:'/goods',
          component:GoodList
        },
        {
          path:'/categories',
          component: CategoryList
        },
        {
          path: '/users',
          component:UserList
        },
        {
          path:'/rights',
          component: RightList
        },
        {
          path:'/roles',
          component:RoleList
        }
      ]
    }
]

const router = new VueRouter({
  mode: 'history',
  routes
});

router.beforeEach( async (to, from, next) => {

    const token = sessionStorage.getItem('token');

    if (to.path === '/login' || to.path === '/register' || to.path === '/loginRegister'){

        if (!isEmpty(token)){
            return next('/home')
        }
        return next();
    }

    if (store.getters.userInfo === null){

      await store.dispatch(Methods.GET_USER_INFO);
    }

    if (store.getters.leftMenus === null){

      await store.dispatch(Methods.GET_Left_Menu);
    }


    next()
});

export default router
